package com.accp.hotevent;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class Base64ImageConverter {
    public static void main(String[] args) {
        String imagePath = "C:\\Users\\17400\\Desktop\\images\\2.bmp";

        // 将图片转换为Base64字符串
        String base64String = imageToBase64(imagePath);
        System.out.println(base64String);
        System.out.println(base64String.length());

        // 将Base64字符串转换为图片
//        String outputImagePath = "C:\\Users\\17400\\Desktop\\images\\111.bmp";
//        base64ToImage(base64String, outputImagePath);
//        System.out.println("图片已保存至: " + outputImagePath);
    }

    public static String imageToBase64(String imagePath) {
        try {
            // 读取图片文件为字节数组
            Path path = Paths.get(imagePath);
            byte[] imageBytes = Files.readAllBytes(path);

            // 对字节数组进行Base64编码
            String base64String = Base64.getEncoder().encodeToString(imageBytes);

            return base64String;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void base64ToImage(String base64String, String outputImagePath) {
        try {
            // 解码Base64字符串为字节数组
            byte[] imageBytes = Base64.getDecoder().decode(base64String);

            // 将字节数组写入输出图片文件
            Path path = Paths.get(outputImagePath);
            Files.write(path, imageBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
